import { number } from "@intlify/core-base";
import { data } from "dom7";
import { ElMessageBox } from "element-plus";
import { saveAs } from "file-saver";
import { defineStore } from "pinia";

export const useSystem = defineStore("useSystem", {
  persist: {
    key: "yyqs-system",
    storage: sessionStorage,
    paths: [""],
  },
  state: () => {
    return {
      permission: {
        currentPage: 1,
        currentIndex: 0, //用来判断是修改还是新增
        pageSize: 10,
        isDialogDisplay: false,
        props: { children: "submenu" },
        defaultSort: { prop: "date", order: "ascending" } as any,
        identity: [
          {
            date: "2022/08/21",
            name: "最高管理权限",
            identifier: "yyqs",
            state: true,
            type: 1,
            authority: [
              "4||1",
              "2||1",
              "1||1",
              "1||2-1",
              "2||2-1",
              "4||2-1",
              "2||2-2",
              "1||2-2",
              "4||2-2",
              "4||2-3",
              "2||2-3",
              "1||2-3",
              "1||2-4",
              "2||2-4",
              "4||2-4",
            ] as any,
            rwd: ["1", "2-1", "2-2", "2-3", "2-4"] as any,
          },
          {
            date: "2022/08/21",
            name: "管理员",
            identifier: "admin",
            state: false,
            type: 2,
            authority: ["4||1", "2||1", "1||1"] as any,
            rwd: ["1"] as any,
          },
          {
            date: "2022/08/21",
            name: "测试员",
            identifier: "test",
            state: true,
            type: 3,
            authority: [] as any,
            rwd: [] as any,
          },
        ],
        identityForm: {
          date: "",
          name: "",
          identifier: "",
          state: false,
          type: 1,
          authority: [] as any,
          rwd: [] as any,
        },
      },
      user: {
        currentPage: 1,
        currentIndex: 0, //用来判断是修改还是新增
        pageSize: 10,
        isDialogDisplay: false,
        props: { children: "submenu" },
        defaultProps: {
          children: "children",
          label: "label",
        } as any,
        selection: [],
        userFileList: [] as any, //导入文件列表
        users: [
          {
            id: 1,
            name: "yyqs",
            sex: 1,
            email: "12345@qq.com",
            date: "2022/08/20",
            identity: "yyqs",
          },
          {
            id: 2,
            name: "test",
            sex: 0,
            email: "12345@qq.com",
            date: "2022/08/20",
            identity: "test",
          },
        ],
        usersForm: {
          id: 0,
          name: "",
          sex: 1,
          email: "",
          date: "",
          identity: "",
        },
      },

      department: {
        currentPage: 1,
        currentIndex: 0, //-1表示没有存在的元素，代表新建
        pageSize: 10,
        isDialogDisplay: false,
        props: { children: "children" },
        selection: [] as any[],
        oldParent: -1,
        departmentFile: [] as any,
        length: 5, //部门总数，用来判断全选
        departments: [
          {
            id: 1,
            name: "1总公司",
            legalRepresentative: "1某",
            phone: "123456",
            email: "12345@qq.com",
            date: "2022/08/20",
            children: [
              {
                id: 2,
                name: "2子公司",
                legalRepresentative: "2某",
                phone: "123456",
                email: "12345@qq.com",
                date: "2022/08/20",
                children: [
                  {
                    id: 4,
                    name: "4叶公司",
                    legalRepresentative: "4某",
                    phone: "123456",
                    email: "12345@qq.com",
                    date: "2022/08/20",
                    children: [],
                    parent: 2,
                  },
                ],
                parent: 1,
              },
              {
                id: 3,
                name: "3子公司",
                legalRepresentative: "3某",
                phone: "123456",
                email: "12345@qq.com",
                date: "2022/08/20",
                children: [
                  {
                    id: 5,
                    name: "5叶公司",
                    legalRepresentative: "5某",
                    phone: "123456",
                    email: "12345@qq.com",
                    date: "2022/08/20",
                    children: [],
                    parent: 3,
                  },
                ],
                parent: 1,
              },
            ],
            parent: 0,
          },
        ],
        departmentForm: {
          id: 0,
          name: "",
          legalRepresentative: "",
          phone: "",
          email: "",
          date: "",
          children: [],
          parent: -1,
        },
      },
    };
  },
  getters: {},
  actions: {
    //权限
    permissionAdd() {
      this.permission.isDialogDisplay = true;
      this.permission.currentIndex = -1; //-1表示新增
      this.permission.identityForm = {
        date: "",
        name: "",
        identifier: "",
        state: false,
        type: 1,
        authority: [] as any,
        rwd: [] as any,
      };
    },
    permissionEditOrDelete(type: number, row: any) {
      let index = this.permission.identity.findIndex(
        (v: { identifier: any }) => v.identifier == row.identifier
      );
      type == 1
        ? (() => {
            console.log(row);
            this.permission.currentIndex = index;
            this.permission.isDialogDisplay = true;
            this.permission.identityForm = JSON.parse(JSON.stringify(row));
          })()
        : (() => {
            ElMessageBox.confirm(
              "注意：拥有该身份的用户将全部变成普通身份，此操作不可逆！",
              "是否删除该身份",
              {
                confirmButtonText: "确认",
                cancelButtonText: "取消",
                showClose: false,
                type: "error",
              }
            )
              .then(() => {
                this.permission.identity.splice(index, 1);
                ElMessage({
                  type: "success",
                  message: "成功删除！",
                  duration: 500,
                });
              })
              .catch(() => {
                ElMessage({
                  type: "info",
                  message: "取消删除！",
                  duration: 500,
                });
              });
          })();
    },
    permissionSaveOrCancel(type: number) {
      type == 1
        ? (() => {
            this.permission.currentIndex == -1
              ? (() => {
                  const date = new Date();
                  this.permission.identityForm.date = date.toLocaleDateString();
                  this.permission.identity.push(
                    JSON.parse(JSON.stringify(this.permission.identityForm))
                  );
                  ElMessage({
                    type: "success",
                    message: "添加成功！",
                    duration: 500,
                  });
                })()
              : (() => {
                  this.permission.identity[this.permission.currentIndex] =
                    JSON.parse(JSON.stringify(this.permission.identityForm));
                  ElMessage({
                    type: "success",
                    message: "修改成功！",
                    duration: 500,
                  });
                })();
          })()
        : ElMessage({
            type: "info",
            message: "取消操作！",
            duration: 500,
          });
      this.permission.isDialogDisplay = false;
    },

    //用户
    userAdd() {
      this.user.isDialogDisplay = true;
      this.user.currentIndex = -1; //-1表示新增
      this.user.usersForm = {
        id: 0,
        name: "",
        sex: 1,
        email: "",
        date: "",
        identity: "",
      };
    },
    userDelete() {
      ElMessageBox.confirm("是否删除所有选中的用户", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        showClose: false,
        type: "error",
      })
        .then(() => {
          this.user.selection.forEach((value) => {
            if (value == 1) return;
            let index = this.user.users.findIndex(
              (v: { id: number }) => v.id == value
            );
            this.user.users.splice(index, 1);
          });
          ElMessage({
            type: "success",
            message: "成功删除！",
            duration: 500,
          });
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "取消删除！",
            duration: 500,
          });
        });
    },
    userEditOrDelete(type: number, row: any) {
      let index = this.user.users.findIndex(
        (v: { name: any }) => v.name == row.name
      );
      type == 1
        ? (() => {
            this.user.currentIndex = index;
            this.user.isDialogDisplay = true;
            this.user.usersForm = JSON.parse(JSON.stringify(row));
          })()
        : (() => {
            ElMessageBox.confirm("是否删除该用户", {
              confirmButtonText: "确认",
              cancelButtonText: "取消",
              showClose: false,
              type: "error",
            })
              .then(() => {
                this.user.users.splice(index, 1);
                ElMessage({
                  type: "success",
                  message: "成功删除！",
                  duration: 500,
                });
              })
              .catch(() => {
                ElMessage({
                  type: "info",
                  message: "取消删除！",
                  duration: 500,
                });
              });
          })();
    },
    userSaveOrCancel(type: number) {
      type == 1
        ? (() => {
            this.user.currentIndex == -1
              ? (() => {
                  //插入id
                  this.user.usersForm.id =
                    this.user.users[this.user.users.length - 1].id + 1;

                  //创建时间
                  const date = new Date();
                  this.user.usersForm.date = date.toLocaleDateString();
                  this.user.users.push(
                    JSON.parse(JSON.stringify(this.user.usersForm))
                  );
                  ElMessage({
                    type: "success",
                    message: "添加成功！",
                    duration: 500,
                  });
                })()
              : (() => {
                  this.user.users[this.user.currentIndex] = JSON.parse(
                    JSON.stringify(this.user.usersForm)
                  );
                  ElMessage({
                    type: "success",
                    message: "修改成功！",
                    duration: 500,
                  });
                })();
          })()
        : ElMessage({
            type: "info",
            message: "取消操作！",
            duration: 500,
          });
      this.user.isDialogDisplay = false;
    },

    //部门
    departmentAdd() {
      this.department.isDialogDisplay = true;
      this.department.currentIndex = -1; //-1表示新增
      this.department.departmentForm = {
        id: 0,
        name: "",
        legalRepresentative: "",
        phone: "",
        email: "",
        date: "",
        children: [],
        parent: -1,
      };
    },
    //递归数据进行删除
    recursiveDelete(id: number, arr: any[], type = 2) {
      if (arr.length != 0) {
        let index = arr.findIndex((v: any) => v.id == id);
        if (index > -1) {
          type == 1
            ? (() => {
                console.log(this.department.oldParent, arr[index].parent);

                if (this.department.oldParent == arr[index].parent)
                  arr.splice(index, 1);
              })()
            : (() => {
                arr.splice(index, 1);
                return;
              })();
        }
        for (let i in arr) {
          this.recursiveDelete(id, arr[i].children, type);
        }
      }
      return;
    },
    //批量删除
    departmentsDelete() {
      ElMessageBox.confirm("是否删除所有选中的部门", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        showClose: false,
        type: "error",
      })
        .then(() => {
          this.department.selection.forEach((value) => {
            if (value == 1) return;
            this.recursiveDelete(value, this.department.departments);
            this.department.length--;
          });
          ElMessage({
            type: "success",
            message: "成功删除！",
            duration: 500,
          });
        })
        .catch(() => {
          ElMessage({
            type: "info",
            message: "取消删除！",
            duration: 500,
          });
        });
    },

    departmentEditOrDelete(type: number, row: any) {
      type == 1
        ? (() => {
            this.department.currentIndex = 0;
            this.department.isDialogDisplay = true;
            this.department.oldParent = JSON.parse(JSON.stringify(row.parent)); //记录旧的父节点，用来判断节点变化
            this.department.departmentForm = JSON.parse(JSON.stringify(row));
          })()
        : (() => {
            ElMessageBox.confirm("是否删除该部门", {
              confirmButtonText: "确认",
              cancelButtonText: "取消",
              showClose: false,
              type: "error",
            })
              .then(() => {
                this.recursiveDelete(row.id, this.department.departments);
                this.department.length--;
                ElMessage({
                  type: "success",
                  message: "成功删除！",
                  duration: 500,
                });
              })
              .catch(() => {
                ElMessage({
                  type: "info",
                  message: "取消删除！",
                  duration: 500,
                });
              });
          })();
    },
    //递归添加
    recursiveUpdate(parent: number, arr: any[], data: any) {
      let index = arr.findIndex((v: any) => v.id == parent);
      if (index > -1) {
        //新增或者修改
        this.department.currentIndex == -1
          ? arr[index].children.push(data)
          : (() => {
              //判断父节点是否变化
              if (this.department.oldParent == parent) {
                let i = arr[index].children.findIndex(
                  (v: any) => v.id == data.id
                );
                arr[index].children[i] = data;
              } else {
                //先添加再删除原来的部分，防止数组变化导致下标报错
                arr[index].children.push(data);
                this.recursiveDelete(data.id, this.department.departments, 1);
              }
            })();
        return;
      }
      for (let i in arr) {
        this.recursiveUpdate(parent, arr[i].children, data);
      }
    },
    departmentSaveOrCancel(type: number) {
      type == 1
        ? (() => {
            this.department.currentIndex == -1
              ? (() => {
                  //创建时间
                  const date = new Date();
                  this.department.departmentForm.date =
                    date.toLocaleDateString();

                  //插入id
                  this.department.departmentForm.id = date.getTime();

                  this.recursiveUpdate(
                    JSON.parse(
                      JSON.stringify(this.department.departmentForm.parent)
                    ),
                    this.department.departments,
                    JSON.parse(JSON.stringify(this.department.departmentForm))
                  );
                  this.department.length++;
                  ElMessage({
                    type: "success",
                    message: "添加成功！",
                    duration: 500,
                  });
                })()
              : (() => {
                  this.department.departmentForm.parent == 0
                    ? (this.department.departments[0] = JSON.parse(
                        JSON.stringify(this.department.departmentForm)
                      ))
                    : this.recursiveUpdate(
                        JSON.parse(
                          JSON.stringify(this.department.departmentForm.parent)
                        ),
                        this.department.departments,
                        JSON.parse(
                          JSON.stringify(this.department.departmentForm)
                        )
                      );
                  ElMessage({
                    type: "success",
                    message: "修改成功！",
                    duration: 500,
                  });
                })();
          })()
        : ElMessage({
            type: "info",
            message: "取消操作！",
            duration: 500,
          });
      this.department.isDialogDisplay = false;
    },

    //获取复选框选取的全部节点
    selectionChange(selection: any) {
      //用于批量删除

      this.user.selection = selection.map((v: any) => {
        return v.id;
      });
      this.department.selection = selection.map((v: any) => {
        return v.id;
      });
    },

    //导出json文件
    exportJson(type: number) {
      type == 1
        ? (() => {
            const blob = new Blob([JSON.stringify(this.user.users)], {
              type: "text/plain;charset=utf-8",
            });
            saveAs(blob, "用户.json");
          })()
        : (() => {
            const blob = new Blob(
              [JSON.stringify(this.department.departments)],
              {
                type: "text/plain;charset=utf-8",
              }
            );
            saveAs(blob, "部门.json");
          })();
    },
  },
});
